package com.sanjiahantang.uilibrary.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.sanjiahantang.uilibrary.R;
import com.sanjiahantang.uilibrary.dialog.CommonDialog;
import com.sanjiahantang.uilibrary.views.zoomimage.MyViewPager;
import com.sanjiahantang.uilibrary.views.zoomimage.PicViewPagerAdapter;
import com.squareup.picasso.Picasso;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;



/**
 * Created by sks on 2015/9/16.
 */
public class Utils {


    public static final int NO_NETWORK_STATE = 0;     //无网络
    public static final int WIFI_STATE = 1;     //wifi


    /*
     * 取得应用的版本号,就是哪个版本,
     */
    public static String longVersionName(Context context) {
        String mVersion = null;
        if (mVersion == null) {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi;
            try {
                pi = pm.getPackageInfo(context.getPackageName(), 0);
                mVersion = pi.versionName;

            } catch (NameNotFoundException e) {
                mVersion = ""; // failed, ignored
            }
        }
        return mVersion;
    }
    /*
     * 取得应用的版本号,就是修改次.
     */
    public static int longVersionCode(Context context) {
        int mVersionCode = 0;
        if (mVersionCode == 0) {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi;
            try {
                pi = pm.getPackageInfo(context.getPackageName(), 0);
                mVersionCode = pi.versionCode;

            } catch (NameNotFoundException e) {
                mVersionCode = 0; // failed, ignored
            }
        }
        return mVersionCode;
    }


    //使用Toast
    static Toast toast = null;
    public static void showToast(Context context, String message) {
        if (context != null && !TextUtils.isEmpty(message)){
            try {
                if(toast != null){
                    toast.setText(message);
                }else{
                    toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
                }
                toast.show();
            } catch (Exception e) {
                //解决在子线程中调用Toast的异常情况处理
                Looper.prepare();
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }
    }
    //客户端认证加密字符串
    public static String AppMD5String(Context context,String model,String action){
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            date = df.parse(df.format(new Date()));
        }catch (ParseException e){}
        long time = date.getTime();
//        long timecurrentTimeMillis = System.currentTimeMillis();
        return md5(model + action + time + "99-k");
    }
    //字符串md5加密
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 判断当前是否有可用的网络以及网络类型 0：无网络 1：WIFI 2：CMWAP 3：CMNET
     *
     * @param context
     * @return
     */
    public static int isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return 0;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetworkInfo netWorkInfo = info[i];
                        if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            String extraInfo = netWorkInfo.getExtraInfo();
                            if ("cmwap".equalsIgnoreCase(extraInfo)
                                    || "cmwap:gsm".equalsIgnoreCase(extraInfo)) {
                                return 2;
                            }
                            return 3;
                        }
                    }
                }
            }
        }
        return 0;
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale - 0.5f);
    }

    /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    //时间戳转时间
    public static String time(Context context,long s){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date(s*1000));
        return date;
    }

    //时间戳转时间
    public static String time2(Context context,long s){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date(s*1000));
        return date;
    }



    public static Boolean checkIsVisible(Context context, View view) {
        // 如果已经加载了，判断广告view是否显示出来，然后曝光
        int screenWidth = getScreenMetrics(context).x;
        int screenHeight = getScreenMetrics(context).y;
        Rect rect = new Rect(0, 0, screenWidth, screenHeight);
        int[] location = new int[2];
        view.getLocationInWindow(location);
        //view已不在屏幕可见区域;
        return view.getLocalVisibleRect(rect);
    }

    /**
     * 获取屏幕宽度和高度，单位为px
     * @param context
     * @return
     */
    public static Point getScreenMetrics(Context context){
        DisplayMetrics dm =context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);
    }

    /**
     * 改状态栏样式
     * @param activity
     */
    public static void showStatusBar(Activity activity){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
//            // Translucent status bar
//            window.setFlags(
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            // Translucent navigation bar
//            window.setFlags(
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

//            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.setStatusBarColor(Color.TRANSPARENT);
//                window.setNavigationBarColor(Color.TRANSPARENT);
            }

        }
    }

    /**
     * 恢复态栏样式
     * @param activity
     */
    public static void recoverStatusBar(Activity activity){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            // Translucent status bar
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // Translucent navigation bar
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    public static void alertScreenInfo(Activity activity){
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）
        int height = metric.heightPixels;  // 屏幕高度（像素）
        float density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
        String msg = "width : " + width + ";\r\n"
                + "height : " + height + ";\r\n"
                +"density : " + density + ";\r\n"
                + "densityDpi : " + densityDpi + ";\r\n";
        new AlertDialog.Builder(activity)
                .setMessage(msg)
                .create()
                .show();
    }

    /**
     * 获取拼音的首字母（大写）
     * @param pinyin
     * @return
     */
    public static String getFirstLetter(final String pinyin){
        if (TextUtils.isEmpty(pinyin)) return "定位";
        String c = pinyin.substring(0, 1);
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c).matches()){
            return c.toUpperCase();
        } else if ("0".equals(c)){
            return "定位";
        } else if ("1".equals(c)){
            return "历史";
        } else if ("2".equals(c)){
            return "热门";
        }
        return "定位";
    }

    /**
     * 提取出城市或者县
     * @param city
     * @param district
     * @return
     */
    public static String extractLocation(final String city, final String district){
        return district.contains("县") ? district.substring(0, district.length() - 1) : city.substring(0, city.length() - 1);
    }





    /**
     * 图片展示
     * @param context
     * @param url 地址
     * @param placeHolder 默认
     */
    private static Dialog picDialog;
    private static PicViewPagerAdapter picViewPagerAdapter;
    public static void showPicDialog(Activity context,String url,int placeHolder){
        if (picDialog != null){
            picDialog.dismiss();
        }
        picDialog = new Dialog(context,R.style.dialog_common);
        picViewPagerAdapter = new PicViewPagerAdapter(context,url);
        picViewPagerAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (picDialog != null){
                    picDialog.dismiss();
                }
            }
        });
        final MyViewPager viewPager = new MyViewPager(context);
        viewPager.setAdapter(picViewPagerAdapter);
        picDialog.setContentView(viewPager);
        picDialog.show();
    }


  //  public static SendMessageDialog myMessgaeDialog;
    private static CommonDialog myDialog;
    //启动自定义dialog
    public static void showDialog(Activity context,String title,String content,String leftText,String rightText,int type,
                                  View.OnClickListener onClickListener){
        if (myDialog != null){
            myDialog.dismiss();
        }
        myDialog = new CommonDialog(context, R.style.dialog_common,title,content,leftText,rightText,type,onClickListener);
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.show();
    }

    public static void showDialog(Activity context,String title,String content,String leftText,String rightText,
                             View.OnClickListener onClickListener){
        showDialog(context, title,content,leftText,rightText,0,onClickListener);
    }
//    //messsgae自定义dialog
//    public static void showSendMessageDialog(Activity context,String title,String content,String leftText,String rightText,
//                                             SendMessageDialog.OnSureClickListener onClickListener){
//        myMessgaeDialog = new SendMessageDialog(context, R.style.dialog_common,title,content,leftText,rightText,onClickListener);
//        myMessgaeDialog.setCanceledOnTouchOutside(false);
//        myMessgaeDialog.show();
//    }
    //销毁dialog
    public static void dismissDialog(){
        if (myDialog != null && myDialog.isShowing()){
            myDialog.dismiss();
        }

    }

    public static void onDialogDismiss(DialogInterface.OnDismissListener onDismissListener){
        if (myDialog != null){
            myDialog.setOnDismissListener(onDismissListener);
        }
    }
//    public static void dismissMessageDialog(){
//        if (myMessgaeDialog.isShowing()){
//            myMessgaeDialog.dismiss();
//        }
//    }
    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                int per = 100;
                bitmap.compress(Bitmap.CompressFormat.JPEG, per, baos);


                while (baos.toByteArray().length > 512 * 1024){
                    per = per - 5;
                    bitmap.compress(Bitmap.CompressFormat.JPEG, per, baos);
                }

                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 通过uri获取图片并进行压缩
     *
     * @param uri
     */
    public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
        InputStream input = ac.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
        //图片分辨率以480x800为标准
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = ac.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 40, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static List<Integer> removeDuplicate(List<Integer> list) {
        Set<Integer> set = new HashSet<Integer>();
        List<Integer> newList = new ArrayList<Integer>();
        for (Iterator<Integer> iter = list.iterator(); iter.hasNext();) {
            Integer element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        return newList;
    }

    /**
     * String转float
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static float toFloat(String obj) {
        if (obj != null) {
            try {
                obj = obj.trim();
                return Float.valueOf(obj);
            } catch (Exception e) {
            }
        }

        return 0F;
    }

    /**
     * 字符串转布尔
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * String转long
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    public static String getLast4(String bankCardNo) {
        if (TextUtils.isEmpty(bankCardNo)){
            return "";
        }

        if (bankCardNo.length() < 4){
            return bankCardNo;
        }

        return bankCardNo.substring(bankCardNo.length() - 4);
    }

    /**
     * 作者：19snow93
     链接：https://www.jianshu.com/p/c138055af5d2
     來源：简书
     著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
     * @param recyclerView
     * @return
     */
    public static boolean isVisBottom(RecyclerView recyclerView){
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //屏幕中最后一个可见子项的position
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        //当前屏幕所看到的子项个数
        int visibleItemCount = layoutManager.getChildCount();
        //当前RecyclerView的所有子项个数
        int totalItemCount = layoutManager.getItemCount();
        //RecyclerView的滑动状态
        int state = recyclerView.getScrollState();
        if(visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == recyclerView.SCROLL_STATE_IDLE){
            return true;
        }else {
            return false;
        }
    }
}
